package cn.sciento.boot.api.customize.compile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;

public class MemoryByteCode extends SimpleJavaFileObject {
  private static final char PKG_SEPARATOR = '.';
  
  private static final char DIR_SEPARATOR = '/';
  
  private static final String CLASS_FILE_SUFFIX = ".class";
  
  private ByteArrayOutputStream byteArrayOutputStream;
  
  public MemoryByteCode(String className) {
    super(URI.create("byte:///" + className.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);
  }
  
  public MemoryByteCode(String className, ByteArrayOutputStream byteArrayOutputStream) throws URISyntaxException {
    this(className);
    this.byteArrayOutputStream = byteArrayOutputStream;
  }
  
  public OutputStream openOutputStream() throws IOException {
    if (this.byteArrayOutputStream == null)
      this.byteArrayOutputStream = new ByteArrayOutputStream(); 
    return this.byteArrayOutputStream;
  }
  
  public byte[] getByteCode() {
    return this.byteArrayOutputStream.toByteArray();
  }
  
  public String getClassName() {
    String className = getName();
    className = className.replace('/', '.');
    className = className.substring(1, className.indexOf(".class"));
    return className;
  }
}
